package com.itheima.interceptor;


import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;

import com.itheima.vo.EmployeeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author itheima
 * @since 2022-04-09
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private RedisTemplate<Object, Object> redisTemplate;

    public AuthInterceptor() {

    }

    public AuthInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        EmployeeVO employeeVO = (EmployeeVO) redisTemplate.opsForValue().get(token);

        if (employeeVO != null) {
            String id = employeeVO.getId();
            TokenHolder.setCurrentId(id);
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("没登录")));
        return false;
    }
}
